package config

import (
	"io/ioutil"
	"os"
	"path/filepath"

	"gopkg.in/yaml.v2"
)

// AIConfig represents the structure of ai.yaml
type AIConfig struct {
	Current struct {
		Alias    string            `yaml:"alias"`
		Type     string            `yaml:"type"`
		Endpoint string            `yaml:"endpoint"`
		Headers  map[string]string `yaml:"headers"`
	} `yaml:"current"`
}

// GetAIConfigPath returns the path to ai.yaml
func GetAIConfigPath() (string, error) {
	home, err := os.UserHomeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(home, ".pwsh", "ai.yaml"), nil
}

// LoadAIConfig loads the config from ai.yaml
func LoadAIConfig() (*AIConfig, error) {
	path, err := GetAIConfigPath()
	if err != nil {
		return nil, err
	}
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return &AIConfig{}, nil // Return empty config if file doesn't exist
	}
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	var config AIConfig
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, err
	}
	return &config, nil
}

// SaveAIConfig saves the config to ai.yaml
func SaveAIConfig(config *AIConfig) error {
	path, err := GetAIConfigPath()
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
		return err
	}
	data, err := yaml.Marshal(config)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(path, data, 0644)
}
